/*
 * 文件名：StartBuildController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月26日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.ic.web;


import com.github.pagehelper.Page;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.mgr.bpa.service.InnerAgrtService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.ic.domain.StartBuildDomain;
import top.infopub.mgr.ic.service.StartBuildService;
import top.infopub.mgr.ic.vo.StartBuildVo;
import top.infopub.mgr.mkt.service.DiscloseProService;
import top.infopub.mgr.mkt.vo.DiscloseProVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.ic.StartBuildAtt;
import top.infopub.model.ic.StartBuildRisk;
import top.infopub.model.mkt.DisclosePro;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 开工审批
 * @author wangw
 * @version 2020年3月30日
 * @see StartBuildController
 * @since
 */
@Controller
@RequestMapping("/startBuild")
public class StartBuildController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private DiscloseProService discloseProService;
    
    @Autowired
    private InnerAgrtService innerAgrtService;
    
    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private StartBuildService startBuildService;

    /**
     * 开工审批列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "ic/lay-startBuild-list";
    }

    /**
     * 开工审批列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<StartBuildDomain> queryDataByCondition(StartBuildVo startBuildVo,
                                                        ParamPage paramPage) {
        Page<StartBuildDomain> page = new Page<StartBuildDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (startBuildVo.getEndDate() != null) {
            startBuildVo.setEndDate(DateUtils.addDays(startBuildVo.getEndDate(), 1));
        }
        //查询时，结束日期增加一天
        if (startBuildVo.getPlanStartEndDate() != null) {
            startBuildVo.setPlanStartEndDate(DateUtils.addDays(startBuildVo.getPlanStartEndDate(), 1));
        }
        //查询时，结束日期增加一天
        if (startBuildVo.getPlanEndEndDate() != null) {
            startBuildVo.setPlanEndEndDate(DateUtils.addDays(startBuildVo.getPlanEndEndDate(), 1));
        }
        page = startBuildService.selectByDomainWhere(page, startBuildVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 开工审批-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<StartBuildDomain> queryMyCheckDataByCondition(StartBuildVo startBuildVo,
                                                               ParamPage paramPage) {
        Page<StartBuildDomain> page = new Page<StartBuildDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (startBuildVo.getEndDate() != null) {
            startBuildVo.setEndDate(DateUtils.addDays(startBuildVo.getEndDate(), 1));
        }
        //查询时，结束日期增加一天
        if (startBuildVo.getPlanStartEndDate() != null) {
            startBuildVo.setPlanStartEndDate(DateUtils.addDays(startBuildVo.getPlanStartEndDate(), 1));
        }
        //查询时，结束日期增加一天
        if (startBuildVo.getPlanEndEndDate() != null) {
            startBuildVo.setPlanEndEndDate(DateUtils.addDays(startBuildVo.getPlanEndEndDate(), 1));
        }
        startBuildVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = startBuildService.selectMyCheckByDomainWhere(page, startBuildVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 开工审批-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询交底的记录
        DisclosePro disclosePro = new DisclosePro();
        disclosePro.setProcessStatus("9");
        List<DisclosePro> disclosePros = discloseProService.selectByEntityWhere(disclosePro);
        request.setAttribute("disclosePros", disclosePros);
        return "ic/lay-startBuild-add";
    }

    /**
     * 根据id查询开工审批详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 开工审批Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        StartBuildVo startBuild = startBuildService.queryById(id);
        map.put("startBuild", startBuild);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, startBuild.getProcessId());
        return new ModelAndView("ic/lay-startBuild-detail", map);
    }

    /**
     * 新增开工审批
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request,StartBuildVo startBuild) {
        String[] fileAtt = request.getParameterValues("fileAtt");
        //开工审批表处理
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        startBuild.setId(id);
        startBuild.setAddBy(vo.getId());
        startBuild.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("ic_start_build");
        startBuild.setCodes(code);
        // 处理processId
        startBuild.setProcessId(IdFactory.getUUIDUpper());
        startBuild.setProcessStatus("1");//审批中
        startBuild.setUptBy(vo.getId());
        startBuild.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //风险集合
        List<StartBuildRisk> startBuildRisks = new ArrayList<StartBuildRisk>();
        for(StartBuildRisk startBuildRisk:startBuild.getStartBuildRisks()){
            startBuildRisk.setId(IdFactory.getUUIDUpper());
            startBuildRisk.setStartBuildId(id);
            startBuildRisk.setAddBy(vo.getId());
            startBuildRisk.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            startBuildRisks.add(startBuildRisk);
        }
        //上传附件
        List<StartBuildAtt> startBuildAtts = new ArrayList<StartBuildAtt>();
        //附件材料
        if (fileAtt != null) {
            for (String file : fileAtt) {
                StartBuildAtt startBuildAtt = createFileAtt(vo, id, file);
                startBuildAtts.add(startBuildAtt);
            }
        }
        startBuildService.saveStartBuild(startBuild, startBuildRisks, startBuildAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "投建管理 -开工审批：项目名=" + startBuild.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    private StartBuildAtt createFileAtt(AuthorizationVO vo, String startBuildId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        StartBuildAtt fileAtt = new StartBuildAtt();
        fileAtt.setId(fileAttStr[1]);
        fileAtt.setStartBuildId(startBuildId);//项目id
        String fileName = fileAttStr[0].substring(0, fileAttStr[0].lastIndexOf("."));
        String suffix = fileAttStr[0].substring(fileAttStr[0].lastIndexOf("."),
            fileAttStr[0].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[2]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 根据id查询交底记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getDiscloseProById")
    @ResponseBody
    public Map<String, Object> getDiscloseProById(HttpServletRequest request,String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            DiscloseProVo disclosePro = discloseProService.selectById(id);
            map.put("disclosePro", disclosePro);
        }
        catch (Exception e) {
            log.error("查询交底记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }
    
    /**
     * 根据项目编号查询内部协议
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/getInnerAgrtByProCode")
//    @ResponseBody
//    public Map<String, Object> getInnerAgrtByProCode(HttpServletRequest request,String proCode) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        try {
//            //带出内部协议的信息
//            Map<String, Object> mapWhere = new HashMap<String, Object>();
//            mapWhere.put("proCode", proCode);
//            mapWhere.put("processStatus", "9");
//            mapWhere.put("orderCondition", "ADD_TIME desc");
//            List<InnerAgrt> innerAgrts = innerAgrtService.selectByMapWhere(mapWhere);
//            if (CollectionUtils.isNotEmpty(innerAgrts)) {
//                map.put("innerAgrt", innerAgrts.get(0));
//                CoopInfo coopInfo = coopInfoService.selectByPrimaryKey(innerAgrts.get(0).getSgCoopId());
//                map.put("coopInfo", coopInfo);
//            }else {
//                map.put("innerAgrt", "");
//            }
//        }
//        catch (Exception e) {
//            log.error("查询内部协议记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "startBuildAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

}
